package com.liuboya.common;

import com.liuboya.weibomodel.model.common.http.FromBodyEntry;
import com.liuboya.weibomodel.model.common.http.RequestHeader;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 描述:
 *
 * <p>
 *
 * @author yeyuan
 * @date 2020-01-10 11:56
 */
@Slf4j
public class OkhttpUtils {

    private static final ConnectionPool CONNECTION = new ConnectionPool(5, 5, TimeUnit.SECONDS);

    private static final OkHttpClient.Builder COMMON_BUILDER = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .followRedirects(true)
            .writeTimeout(10, TimeUnit.SECONDS)
            .retryOnConnectionFailure(false)
            .connectionPool(CONNECTION);

    /**
     * Get请求,返回请求之后的body,一般来说即请求之后的json信息
     *
     * @param url               url
     * @param requestHeaderList 请求头
     * @return 返回结果
     */
    public static String commonGet(String url, List<RequestHeader> requestHeaderList, Proxy proxy) {
        return commonOkHttp("GET", url, new ArrayList<>(), requestHeaderList, proxy);
    }

    /**
     * Post请求,返回请求之后的body,一般来说即请求之后的json信息
     * FormData 形式
     *
     * @param url               url
     * @param requestHeaderList 请求头
     * @param fromBodyEntryList 请求体
     * @param proxy             是否挂代理
     * @return 返回结果
     */
    public static String commonPost(String url, List<FromBodyEntry> fromBodyEntryList, List<RequestHeader> requestHeaderList, Proxy proxy) {
        return commonOkHttp("POST", url, fromBodyEntryList, requestHeaderList, proxy);
    }

    private static String commonOkHttp(String getOrPost, String url, List<FromBodyEntry> fromBodyEntryList, List<RequestHeader> requestHeaderList, Proxy proxy) {
        Request.Builder builder = new Request.Builder();
        //填充请求头
        requestHeaderList.forEach(requestHeader -> builder.addHeader(requestHeader.getName(), requestHeader.getValue()));
        //代理信息
        if (Objects.nonNull(proxy)) {
            COMMON_BUILDER.proxy(proxy);
        }
        //区分POST和GET方法
        Request request;
        if ("POST".equals(getOrPost)) {
            FormBody.Builder formBuilder = new FormBody.Builder();
            fromBodyEntryList.forEach(fromBodyEntry -> formBuilder.add(fromBodyEntry.getName(), fromBodyEntry.getValue()));
            FormBody formBody = formBuilder.build();
            request = builder.post(formBody).url(url).build();
        } else if ("GET".equals(getOrPost)) {
            request = builder.get().url(url).build();
        } else {
            return null;
        }
        try (ResponseBody responseBody = COMMON_BUILDER.build().newCall(request).execute().body()) {
            if (Objects.nonNull(responseBody)) {
                return responseBody.string();
            }
        } catch (IOException e) {
            log.error("调用okhttp通用方法失败，地址：{},原因：{}", url, e.getMessage(), e);
        }
        return null;
    }
}
